package com.xxx.nio.udp;

import com.xxx.nio.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

/**
 * UDP是无连接的，client发送数据时不管Server是否开启
 */
public class Server {

    public static void main(String[] args) {
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.socket().bind(new InetSocketAddress(9999));
            System.out.println("waiting...");
            ByteBuffer buffer = ByteBuffer.allocate(16);
            channel.receive(buffer);  // receive()方法接收Client发送过来的数据，存入ByteBuffer，但如果数据超过buffer大小，多出来的数据默认会被丢弃
            buffer.flip();
            ByteBufferUtil.debugAll(buffer);  // 打印buffer
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
